import { getToken, removeToken } from '@/utils/auth'
import { processPermission, resetRoutes } from '@/router'

const defaultState = () => {
    return {
        token: getToken(),
        avatar: {},
        pageRights: new Map()
    }
}

const getters = {
    pageRights: state => {
        return state.pageRights
    }
}

const mutations = {
    setAvatar(state, avatar) {
        state.avatar = avatar
    },
    setToken(state, token) {
        state.token = token
    },
    resetToken(state) {
        state.token = undefined
    },
    reset: state => {
        state = Object.assign({}, state, defaultState())
    },
    setRights(state, rights) {
        state.pageRights = rights
    }
}

const actions = {
    resetToken({ commit, state }) {
        removeToken()
        resetRoutes()
        commit('resetToken')
        commit('reset')
    },
    processInfo({ commit, state }, info = {}) {
        commit('setAvatar', info)
        const menus = info.menus || []
        processPermission(menus)

        const permissions = info.button || []
        const m = new Map()
        permissions.forEach(p => {
            m.set(p.code, null)
        })
        commit('setRights', m)
    }
}

export default {
    namespaced: true,
    state: defaultState(),
    getters,
    mutations,
    actions
}
